<?php
/**
 * WordPress Spider Monitor - 安装文件
 * 
 * 此文件在插件激活时自动执行，用于创建数据库表
 * 
 * @package WordPress Spider Monitor
 * @author Eric
 * @version 3.0.0
 * @link https://zibovip.top
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 确保WordPress函数可用
if (!function_exists('dbDelta')) {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
}

/**
 * 插件安装类
 */
class WP_Spider_Monitor_Installer {
    
    /**
     * 插件版本
     */
    const VERSION = '3.0.0';
    
    /**
     * 数据库版本
     */
    const DB_VERSION = '3.0.0';
    
    /**
     * 安装选项名称
     */
    const VERSION_OPTION = 'wp_spider_monitor_version';
    const DB_VERSION_OPTION = 'wp_spider_monitor_db_version';
    
    /**
     * 构造函数
     */
    public function __construct() {
        // 注册激活和停用钩子
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // 添加升级检查
        add_action('plugins_loaded', array($this, 'check_upgrade'));
    }
    
    /**
     * 插件激活时执行
     */
    public function activate() {
        // 检查WordPress版本
        if (version_compare(get_bloginfo('version'), '5.0', '<')) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die(
                __('WordPress Spider Monitor 需要 WordPress 5.0 或更高版本。', 'wp-spider-monitor'),
                __('插件激活失败', 'wp-spider-monitor'),
                array('back_link' => true)
            );
        }
        
        // 检查PHP版本
        if (version_compare(PHP_VERSION, '7.4', '<')) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die(
                __('WordPress Spider Monitor 需要 PHP 7.4 或更高版本。', 'wp-spider-monitor'),
                __('插件激活失败', 'wp-spider-monitor'),
                array('back_link' => true)
            );
        }
        
        // 创建数据库表
        $this->create_tables();
        
        // 插入默认数据
        $this->insert_default_data();
        
        // 更新版本信息
        update_option(self::VERSION_OPTION, self::VERSION);
        update_option(self::DB_VERSION_OPTION, self::DB_VERSION);
        
        // 设置默认选项
        $this->set_default_options();
        
        // 刷新重写规则
        flush_rewrite_rules();
        
        // 记录激活日志
        error_log('WordPress Spider Monitor 插件已激活，版本: ' . self::VERSION);
    }
    
    /**
     * 插件停用时执行
     */
    public function deactivate() {
        // 清理定时任务
        wp_clear_scheduled_hook('wp_spider_monitor_cleanup');
        wp_clear_scheduled_hook('wp_spider_monitor_daily_stats');
        
        // 记录停用日志
        error_log('WordPress Spider Monitor 插件已停用');
    }
    
    /**
     * 检查是否需要升级
     */
    public function check_upgrade() {
        $current_version = get_option(self::VERSION_OPTION, '1.0.0');
        $current_db_version = get_option(self::DB_VERSION_OPTION, '1.0.0');
        
        // 检查插件版本升级
        if (version_compare($current_version, self::VERSION, '<')) {
            $this->upgrade_plugin($current_version, self::VERSION);
            update_option(self::VERSION_OPTION, self::VERSION);
        }
        
        // 检查数据库版本升级
        if (version_compare($current_db_version, self::DB_VERSION, '<')) {
            $this->upgrade_database($current_db_version, self::DB_VERSION);
            update_option(self::DB_VERSION_OPTION, self::DB_VERSION);
        }
    }
    
    /**
     * 创建数据库表
     */
    private function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // 1. 蜘蛛访问记录表
        $table_visits = $wpdb->prefix . 'spider_visits';
        $sql_visits = "CREATE TABLE IF NOT EXISTS `{$table_visits}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            spider_name varchar(100) NOT NULL,
            bot_type varchar(50) DEFAULT 'unknown',
            user_agent text NOT NULL,
            ip_address varchar(45) NOT NULL,
            url varchar(500) NOT NULL,
            referer varchar(500),
            visit_time datetime DEFAULT CURRENT_TIMESTAMP,
            response_code int(3) DEFAULT 200,
            response_time decimal(10,3) DEFAULT 0.000,
            page_title varchar(255),
            request_method varchar(10) DEFAULT 'GET',
            content_type varchar(100),
            content_length int(11),
            server_name varchar(100),
            query_string text,
            user_agent_hash varchar(32),
            session_id varchar(100),
            is_mobile tinyint(1) DEFAULT 0,
            device_type varchar(20) DEFAULT 'desktop',
            os varchar(50),
            browser varchar(50),
            country varchar(2),
            region varchar(50),
            city varchar(50),
            latitude decimal(10,8),
            longitude decimal(11,8),
            is_blocked tinyint(1) DEFAULT 0,
            is_ignored tinyint(1) DEFAULT 0,
            rule_tag varchar(50),
            hostname varchar(255),
            is_verified_bot tinyint(1) DEFAULT 0,
            verified_source varchar(50),
            url_type varchar(50) DEFAULT 'unknown',
            post_id bigint(20) DEFAULT 0,
            is_fake_bot tinyint(1) DEFAULT 0,
            fake_reason varchar(255),
            PRIMARY KEY (id),
            KEY spider_name (spider_name),
            KEY visit_time (visit_time),
            KEY url (url(191)),
            KEY ip_address (ip_address),
            KEY response_code (response_code),
            KEY user_agent_hash (user_agent_hash),
            KEY country (country),
            KEY device_type (device_type),
            KEY is_mobile (is_mobile),
            KEY session_id (session_id),
            KEY is_blocked (is_blocked),
            KEY is_ignored (is_ignored),
            KEY rule_tag (rule_tag),
            KEY url_type (url_type),
            KEY post_id (post_id),
            KEY is_fake_bot (is_fake_bot),
            KEY composite_visit (spider_name, visit_time, response_code),
            KEY composite_url_type (url_type, visit_time),
            KEY composite_spider_url (spider_name, url(191))
        ) {$charset_collate};";
        
        // 2. 蜘蛛统计表
        $table_stats = $wpdb->prefix . 'spider_stats';
        $sql_stats = "CREATE TABLE IF NOT EXISTS `{$table_stats}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            spider_name varchar(100) NOT NULL,
            visit_date date NOT NULL,
            visit_count int(11) DEFAULT 0,
            unique_pages int(11) DEFAULT 0,
            unique_ips int(11) DEFAULT 0,
            total_response_time decimal(10,3) DEFAULT 0,
            avg_response_time decimal(10,3) DEFAULT 0,
            min_response_time decimal(10,3) DEFAULT 0,
            max_response_time decimal(10,3) DEFAULT 0,
            last_visit datetime,
            error_count int(11) DEFAULT 0,
            success_count int(11) DEFAULT 0,
            redirect_count int(11) DEFAULT 0,
            mobile_visits int(11) DEFAULT 0,
            desktop_visits int(11) DEFAULT 0,
            tablet_visits int(11) DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY spider_date (spider_name, visit_date),
            KEY spider_name (spider_name),
            KEY visit_date (visit_date),
            KEY last_visit (last_visit),
            KEY composite_stats (spider_name, visit_date, visit_count)
        ) {$charset_collate};";
        
        // 3. URL推送记录表
        $table_push_urls = $wpdb->prefix . 'spider_push_urls';
        $sql_push_urls = "CREATE TABLE IF NOT EXISTS `{$table_push_urls}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            url varchar(500) NOT NULL,
            post_id bigint(20),
            post_type varchar(20) DEFAULT 'post',
            post_title varchar(255),
            post_date datetime,
            push_time datetime DEFAULT CURRENT_TIMESTAMP,
            status varchar(20) DEFAULT 'pending',
            response_data text,
            response_code int(3),
            response_message varchar(255),
            search_engines text,
            success_engines text,
            failed_engines text,
            total_engines int(11) DEFAULT 0,
            success_count int(11) DEFAULT 0,
            fail_count int(11) DEFAULT 0,
            priority int(11) DEFAULT 5,
            retry_count int(11) DEFAULT 0,
            max_retries int(11) DEFAULT 3,
            next_retry datetime,
            is_scheduled tinyint(1) DEFAULT 0,
            scheduled_time datetime,
            user_id bigint(20),
            user_ip varchar(45),
            user_agent text,
            PRIMARY KEY (id),
            KEY url (url(191)),
            KEY post_id (post_id),
            KEY push_time (push_time),
            KEY status (status),
            KEY post_type (post_type),
            KEY response_code (response_code),
            KEY priority (priority),
            KEY next_retry (next_retry),
            KEY is_scheduled (is_scheduled),
            KEY user_id (user_id),
            KEY composite_push (post_id, status, push_time)
        ) {$charset_collate};";
        
        // 4. 搜索引擎配置表
        $table_push_config = $wpdb->prefix . 'spider_push_config';
        $sql_push_config = "CREATE TABLE IF NOT EXISTS `{$table_push_config}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            engine_name varchar(100) NOT NULL,
            engine_type varchar(50) DEFAULT 'custom',
            api_url varchar(500) NOT NULL,
            api_key varchar(255),
            site_url varchar(255),
            site_token varchar(255),
            is_active tinyint(1) DEFAULT 1,
            is_system tinyint(1) DEFAULT 0,
            push_method varchar(20) DEFAULT 'POST',
            content_type varchar(50) DEFAULT 'application/json',
            headers text,
            request_body text,
            url_parameter varchar(100),
            api_format varchar(20) DEFAULT 'json',
            success_pattern varchar(255),
            error_pattern varchar(255),
            daily_quota int(11) DEFAULT 1000,
            used_quota int(11) DEFAULT 0,
            quota_reset_time varchar(5) DEFAULT '00:00',
            last_push_date date,
            today_pushed int(11) DEFAULT 0,
            total_pushed int(11) DEFAULT 0,
            total_success int(11) DEFAULT 0,
            total_failed int(11) DEFAULT 0,
            success_rate decimal(5,2) DEFAULT 0.00,
            average_response_time decimal(10,3) DEFAULT 0.000,
            timeout_seconds int(11) DEFAULT 30,
            retry_enabled tinyint(1) DEFAULT 1,
            max_retries int(11) DEFAULT 3,
            retry_delay int(11) DEFAULT 5,
            rate_limit int(11) DEFAULT 10,
            rate_limit_period int(11) DEFAULT 60,
            custom_parameters text,
            webhook_url varchar(500),
            created_by bigint(20) DEFAULT 1,
            created_time datetime DEFAULT CURRENT_TIMESTAMP,
            updated_by bigint(20),
            updated_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY engine_name (engine_name),
            UNIQUE KEY engine_type_site (engine_type, site_url),
            KEY is_active (is_active),
            KEY is_system (is_system),
            KEY engine_type (engine_type),
            KEY created_time (created_time),
            KEY updated_time (updated_time),
            KEY quota_status (is_active, daily_quota, used_quota)
        ) {$charset_collate};";
        
        // 5. 推送日志表
        $table_push_log = $wpdb->prefix . 'spider_push_log';
        $sql_push_log = "CREATE TABLE IF NOT EXISTS `{$table_push_log}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            push_id bigint(20),
            engine_id bigint(20),
            engine_name varchar(100),
            url varchar(500) NOT NULL,
            post_id bigint(20),
            request_data text,
            response_data text,
            response_code int(3),
            response_time decimal(10,3) DEFAULT 0.000,
            status varchar(20) DEFAULT 'pending',
            error_message text,
            retry_count int(11) DEFAULT 0,
            ip_address varchar(45),
            user_agent text,
            created_time datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY push_id (push_id),
            KEY engine_id (engine_id),
            KEY url (url(191)),
            KEY post_id (post_id),
            KEY status (status),
            KEY response_code (response_code),
            KEY created_time (created_time),
            KEY composite_log (engine_id, status, created_time)
        ) {$charset_collate};";
        
        // 6. 配额管理表
        $table_quota = $wpdb->prefix . 'spider_quota';
        $sql_quota = "CREATE TABLE IF NOT EXISTS `{$table_quota}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            engine_name varchar(100) NOT NULL,
            engine_type varchar(50) NOT NULL,
            daily_quota int(11) DEFAULT 1000,
            used_quota int(11) DEFAULT 0,
            remaining_quota int(11) DEFAULT 1000,
            quota_date date NOT NULL,
            reset_time time DEFAULT '00:00:00',
            last_reset datetime,
            next_reset datetime,
            is_active tinyint(1) DEFAULT 1,
            created_time datetime DEFAULT CURRENT_TIMESTAMP,
            updated_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY engine_date (engine_type, quota_date),
            KEY engine_name (engine_name),
            KEY quota_date (quota_date),
            KEY is_active (is_active),
            KEY remaining_quota (remaining_quota)
        ) {$charset_collate};";
        
        // 7. 索引状态表
        $table_indexing = $wpdb->prefix . 'spider_indexing_status';
        $sql_indexing = "CREATE TABLE IF NOT EXISTS `{$table_indexing}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            url varchar(500) NOT NULL,
            post_id bigint(20),
            engine_type varchar(50) NOT NULL,
            status varchar(20) DEFAULT 'unknown',
            last_checked datetime,
            first_seen datetime,
            last_spider_visit datetime,
            http_status int(3),
            canonical_url varchar(500),
            robots_meta varchar(100),
            sitemap_included tinyint(1) DEFAULT 0,
            notes text,
            created_time datetime DEFAULT CURRENT_TIMESTAMP,
            updated_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY idx_unique (url(191), engine_type),
            KEY post_id (post_id),
            KEY engine_type (engine_type),
            KEY status (status),
            KEY last_checked (last_checked)
        ) {$charset_collate};";
        
        // 8. 用户主题偏好表
        $table_theme = $wpdb->prefix . 'spider_user_theme';
        $sql_theme = "CREATE TABLE IF NOT EXISTS `{$table_theme}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            theme_name varchar(50) NOT NULL DEFAULT 'modern',
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY user_theme (user_id),
            KEY theme_name (theme_name),
            KEY updated_at (updated_at)
        ) {$charset_collate};";
        
        // 9. URL统计表
        $table_url_stats = $wpdb->prefix . 'spider_url_stats';
        $sql_url_stats = "CREATE TABLE IF NOT EXISTS `{$table_url_stats}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            url varchar(500) NOT NULL,
            post_id bigint(20),
            last_visit datetime,
            visit_count int(11) DEFAULT 0,
            last_status int(3),
            avg_response_time decimal(10,3) DEFAULT 0.000,
            last_spider varchar(100),
            first_seen datetime DEFAULT CURRENT_TIMESTAMP,
            last_status_change datetime,
            PRIMARY KEY (id),
            UNIQUE KEY url_unique (url(191)),
            KEY post_id (post_id),
            KEY last_visit (last_visit),
            KEY last_status (last_status),
            KEY first_seen (first_seen)
        ) {$charset_collate};";
        
        // 10. 蜘蛛拦截规则表
        $table_block_rules = $wpdb->prefix . 'spider_block_rules';
        $sql_block_rules = "CREATE TABLE IF NOT EXISTS `{$table_block_rules}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            spider_name varchar(100),
            ip_address varchar(45),
            ip_range varchar(50),
            block_type enum('name','ip','range','name_ip') NOT NULL DEFAULT 'name',
            is_active tinyint(1) DEFAULT 1,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY spider_name (spider_name),
            KEY ip_address (ip_address),
            KEY block_type (block_type),
            KEY is_active (is_active)
        ) {$charset_collate};";
        
        // 11. 文章爬取统计表
        $table_article_crawl = $wpdb->prefix . 'spider_article_crawl';
        $sql_article_crawl = "CREATE TABLE IF NOT EXISTS `{$table_article_crawl}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            post_type varchar(20) NOT NULL,
            post_title varchar(255),
            post_url varchar(500),
            spider_name varchar(100) NOT NULL,
            crawl_count int(11) DEFAULT 0,
            last_crawl datetime,
            outbound_links int(11) DEFAULT 0,
            inbound_links int(11) DEFAULT 0,
            is_indexed tinyint(1) DEFAULT 0,
            crawl_date date NOT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY post_spider_date (post_id, spider_name, crawl_date),
            KEY post_id (post_id),
            KEY spider_name (spider_name),
            KEY crawl_date (crawl_date),
            KEY post_type (post_type),
            KEY is_indexed (is_indexed)
        ) {$charset_collate};";
        
        // 12. 链接规则表
        $table_link_rules = $wpdb->prefix . 'spider_link_rules';
        $sql_link_rules = "CREATE TABLE IF NOT EXISTS `{$table_link_rules}` (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            rule_key varchar(50) NOT NULL,
            title varchar(100) NOT NULL,
            rule_value text,
            is_enabled tinyint(1) DEFAULT 1,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY rule_key (rule_key),
            KEY is_enabled (is_enabled)
        ) {$charset_collate};";
        
        // 执行SQL语句
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        
        dbDelta($sql_visits);
        dbDelta($sql_stats);
        dbDelta($sql_push_urls);
        dbDelta($sql_push_config);
        dbDelta($sql_push_log);
        dbDelta($sql_quota);
        dbDelta($sql_indexing);
        dbDelta($sql_theme);
        dbDelta($sql_url_stats);
        dbDelta($sql_block_rules);
        dbDelta($sql_article_crawl);
        dbDelta($sql_link_rules);
        
        // 记录创建表的结果
        error_log('WordPress Spider Monitor 数据库表创建完成');
    }
    
    /**
     * 插入默认数据
     */
    private function insert_default_data() {
        global $wpdb;
        
        // 插入默认搜索引擎配置
        $table_config = $wpdb->prefix . 'spider_push_config';
        $site_url = get_site_url();
        
        // 检查是否已有数据
        $existing = $wpdb->get_var("SELECT COUNT(*) FROM `{$table_config}` WHERE is_system = 1");
        if ($existing > 0) {
            return; // 已有数据，跳过
        }
        
        // 插入默认搜索引擎配置
        $engines = array(
            array(
                'engine_name' => '百度推送',
                'engine_type' => 'baidu',
                'api_url' => 'http://data.zz.baidu.com/urls',
                'site_url' => $site_url,
                'push_method' => 'POST',
                'content_type' => 'text/plain',
                'is_system' => 1,
                'success_pattern' => 'success',
                'error_pattern' => 'error'
            ),
            array(
                'engine_name' => '必应推送',
                'engine_type' => 'bing',
                'api_url' => 'https://api.indexnow.org/IndexNow',
                'site_url' => $site_url,
                'push_method' => 'POST',
                'content_type' => 'application/json',
                'is_system' => 1,
                'success_pattern' => '"code":200',
                'error_pattern' => '"code":'
            ),
            array(
                'engine_name' => '谷歌搜索推送',
                'engine_type' => 'google',
                'api_url' => 'https://indexing.googleapis.com/v3/urlNotifications:publish',
                'site_url' => $site_url,
                'push_method' => 'POST',
                'content_type' => 'application/json',
                'is_system' => 1,
                'success_pattern' => '"urlNotificationMetadata"',
                'error_pattern' => '"error"'
            ),
            array(
                'engine_name' => '360搜索推送',
                'engine_type' => '360',
                'api_url' => 'http://info.so.com/urls',
                'site_url' => $site_url,
                'push_method' => 'POST',
                'content_type' => 'text/plain',
                'is_system' => 1,
                'success_pattern' => 'success',
                'error_pattern' => 'error'
            )
        );
        
        foreach ($engines as $engine) {
            $wpdb->insert($table_config, $engine);
        }
        
        // 插入默认链接规则
        $table_rules = $wpdb->prefix . 'spider_link_rules';
        $rules = array(
            array('rule_key' => 'home', 'title' => '首页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'single', 'title' => '文章页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'page', 'title' => '独立页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'category', 'title' => '分类页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'tag', 'title' => '标签页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'search', 'title' => '搜索页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'author', 'title' => '作者页', 'rule_value' => '', 'is_enabled' => 1),
            array('rule_key' => 'feed', 'title' => 'Feed', 'rule_value' => '', 'is_enabled' => 1)
        );
        
        foreach ($rules as $rule) {
            $wpdb->insert($table_rules, $rule);
        }
        
        error_log('WordPress Spider Monitor 默认数据插入完成');
    }
    
    /**
     * 设置默认选项
     */
    private function set_default_options() {
        // 插件设置
        $default_options = array(
            'wp_spider_monitor_max_pages' => 100,
            'wp_spider_monitor_request_interval' => 1,
            'wp_spider_monitor_user_agent' => 'WordPress URL Spider/3.0',
            'wp_spider_monitor_timeout' => 30,
            'wp_spider_monitor_follow_redirects' => true,
            'wp_spider_monitor_check_external_links' => false,
            'wp_spider_monitor_auto_analyze' => true,
            'wp_spider_monitor_mobile_friendly' => true,
            'wp_spider_monitor_email_notifications' => false,
            'wp_spider_monitor_notification_email' => get_option('admin_email'),
            'wp_spider_monitor_notification_frequency' => 'daily',
            'wp_spider_monitor_theme' => 'modern',
            'wp_spider_monitor_cache_duration' => 300,
            'wp_spider_monitor_cleanup_days' => 30,
            'wp_spider_monitor_enable_logging' => true,
            'wp_spider_monitor_log_level' => 'info'
        );
        
        foreach ($default_options as $option => $value) {
            if (get_option($option) === false) {
                add_option($option, $value);
            }
        }
    }
    
    /**
     * 升级插件
     */
    private function upgrade_plugin($from_version, $to_version) {
        // 这里可以添加版本升级逻辑
        error_log("WordPress Spider Monitor 插件从 {$from_version} 升级到 {$to_version}");
    }
    
    /**
     * 升级数据库
     */
    private function upgrade_database($from_version, $to_version) {
        // 这里可以添加数据库升级逻辑
        error_log("WordPress Spider Monitor 数据库从 {$from_version} 升级到 {$to_version}");
    }
    
    /**
     * 检查表是否存在
     */
    public static function check_tables_exist() {
        global $wpdb;
        
        $tables = array(
            $wpdb->prefix . 'spider_visits',
            $wpdb->prefix . 'spider_stats',
            $wpdb->prefix . 'spider_push_urls',
            $wpdb->prefix . 'spider_push_config',
            $wpdb->prefix . 'spider_push_log',
            $wpdb->prefix . 'spider_quota',
            $wpdb->prefix . 'spider_indexing_status',
            $wpdb->prefix . 'spider_user_theme',
            $wpdb->prefix . 'spider_url_stats',
            $wpdb->prefix . 'spider_block_rules',
            $wpdb->prefix . 'spider_article_crawl',
            $wpdb->prefix . 'spider_link_rules'
        );
        
        $missing_tables = array();
        foreach ($tables as $table) {
            if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") != $table) {
                $missing_tables[] = $table;
            }
        }
        
        return $missing_tables;
    }
    
    /**
     * 手动创建表（用于修复）
     */
    public static function create_tables_manually() {
        $installer = new self();
        $installer->create_tables();
        $installer->insert_default_data();
        $installer->set_default_options();
        
        return true;
    }
}

// 初始化安装器
new WP_Spider_Monitor_Installer();

// 提供全局函数供其他文件调用
if (!function_exists('wp_spider_monitor_installer')) {
    function wp_spider_monitor_installer() {
        return new WP_Spider_Monitor_Installer();
    }
}

if (!function_exists('wp_spider_monitor_check_tables')) {
    function wp_spider_monitor_check_tables() {
        return WP_Spider_Monitor_Installer::check_tables_exist();
    }
}

if (!function_exists('wp_spider_monitor_create_tables')) {
    function wp_spider_monitor_create_tables() {
        return WP_Spider_Monitor_Installer::create_tables_manually();
    }
}
